package com.gxist.restful.controller;

import com.gxist.restful.entity.User;
import com.gxist.restful.enums.ResultStatusCode;
import com.gxist.restful.repository.UserJPARepository;
import com.gxist.restful.utils.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserJPARepository userJPARepository;

    /**
     * 查询用户列表
     * @return
     */
    @CrossOrigin
    @GetMapping("/user")
    public List<User> findUserList(){
        return userJPARepository.findAll();
    }

    @GetMapping("/hello")
    public String hello(){
        return "welcome to xifly space";
    }

    @CrossOrigin
    @GetMapping("/users")
    public Object findUserLists(){
        List<User> userList = userJPARepository.findAll();
        ResultMsg msg = new ResultMsg(ResultStatusCode.SUCCESS.getCode(),ResultStatusCode.SUCCESS.getMsg(),userList);
        return msg;
    }

    /**
     * 根据Id查询一个用户
     * @param id
     * @return
     */
    @GetMapping("/user/query/{id}")
    public User findOne(@PathVariable("id") Long id){
        return userJPARepository.findOne(id);
    }

    @GetMapping("/user/queryone/{id}")
    public Object queryOne(@PathVariable("id") Long id){
        return new ResultMsg(ResultStatusCode.SUCCESS.getCode(),ResultStatusCode.SUCCESS.getMsg(),userJPARepository.findOne(id));
    }

    /**
     * 添加用户
     * @param name
     * @param age
     * @param country
     * @return
     */
    @PostMapping("/user")
    public User addUser(@RequestParam("name") String name,@RequestParam("age") int age,@RequestParam("country") String country){
        User user = new User();
        user.setAge(age);
        user.setCountry(country);
        user.setName(name);
        return userJPARepository.save(user);
    }

    /**
     * 删除用户
     * @param id 用户编号
     * @return
     */
    @DeleteMapping("/user/{id}")
    public List<User> deleteUser(@PathVariable("id") Long id){
        userJPARepository.delete(id);
        return userJPARepository.findAll();
    }

    /**
     * 更新用户
     * @param id
     * @param name
     * @param age
     * @param country
     * @return
     */
    @PutMapping("/user/{id}")
    public User updateUser(@PathVariable("id") Long id,@RequestParam("name") String name,@RequestParam("age") int age,@RequestParam("country") String country){
        User user = userJPARepository.findById(id);
        user.setName(name);
        user.setAge(age);
        user.setCountry(country);
        return userJPARepository.save(user);
    }

    /**
     * 根据国家查询用户
     * @param country
     * @return
     */
    @GetMapping("/user/{country}")
    public List<User> findByCountry(@PathVariable("country") String country){
        return userJPARepository.findByCountry(country);
    }

}
